﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL.Entity;
using DAL.Persistencia;

namespace NewTierra.Pages
{
    public partial class VerTarifasPorPeriodo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Session["PeriodoIDTarifasVer"] = 10;
                ViewState["TipoTarifa"] = "";
                VerificaPeriodo();
                RdoTarifa_SelectedIndexChanged(sender, e);
                VerificaBase();
                CarregarDadosTarifas(sender, e);
                CarregarDadosMeal(sender, e);
                CarregarDadosPeriodos(sender, e);
                PreencheTitulos();
            }
        }

        #region Popular Periodos

        protected void CarregarDadosPeriodos(object sender, EventArgs e)
        {
            CarregarPeriodos(sender, e);
        }

        protected void CarregarPeriodos(object sender, EventArgs e)
        {
            try
            {
                PeriodosDAL p = new PeriodosDAL();

                Dictionary<string, string> dadosPeriodos = (Dictionary<string, string>)Session["IdsPeriodosVer"];

                GridTarifasPeriodo.DataSource = p.ListarTodosFds(Convert.ToInt32(Session["Sid"]), Convert.ToInt32(dadosPeriodos["IdMercado"]), Convert.ToInt32(dadosPeriodos["IdBaseTarifaria"]), Convert.ToInt32(dadosPeriodos["IdResponsavel"]));
                GridTarifasPeriodo.DataBind();

                if (GridTarifasPeriodo.PageCount > 0)
                {
                    int i = 0;

                    foreach (GridViewRow row in GridTarifasPeriodo.Rows)
                    {
                        if (row.Cells[0].Text == Session["PeriodoIDTarifasVer"].ToString())
                        {
                            GridTarifasPeriodo.SelectedIndex = i;
                            break;
                        }

                        i++;
                    }
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void GridTarifasPeriodo_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["PeriodoIDTarifasVer"] = GridTarifasPeriodo.SelectedRow.Cells[0].Text;
            CarregarDadosTarifas(sender, e);
            CarregarDadosMeal(sender, e);
        }

        #endregion

        #region Carrega Dados Tarifas

        protected void CarregarDadosTarifas(object sender, EventArgs e)
        {
            CarregarTarifas(sender, e);
        }

        protected void CarregarTarifas(object sender, EventArgs e)
        {
            try
            {
                TarifaDAL t = new TarifaDAL();
                SBasesDAL sbd = new SBasesDAL();
                STarifaBaseDAL stbd = new STarifaBaseDAL();                
                

                if (sbd.ObterPorIdSupplier(Convert.ToInt32(Session["Sid"])).Count() != 0)
                {

                    S_Tarifa_Base st = stbd.ObterPorId(Convert.ToInt32(ViewState["IdTarifaBase"]));

                    if (st != null && ViewState["TipoTarifa"].Equals("Apartamento"))
                    {
                        GridTarifas.DataSource = t.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), "normal", Convert.ToInt32(ViewState["IdTarifaBase"]));
                        GridTarifas.DataBind();
                    }
                    else if (st != null)
                    {
                        GridTarifas.DataSource = t.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), Convert.ToInt32(ViewState["IdTarifaBase"])); 
                        GridTarifas.DataBind();
                    }
                    else
                    {
                        GridTarifas.DataSource = t.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), 0);
                        GridTarifas.DataBind();
                    }

                }
                else if (ViewState["TipoTarifa"].Equals("Apartamento") || ViewState["TipoTarifa"].Equals("porpessoa"))
                {
                    GridTarifas.DataSource = t.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), "normal");
                    GridTarifas.DataBind();                    
                }               

                MergeCells();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void PaginarDadosTarifas(object sender, GridViewPageEventArgs e)
        {
            //Realiza a paginação
            GridTarifas.PageIndex = e.NewPageIndex;
            CarregarDadosTarifas(sender, e); //Atualizar os dados do GridView
        }

        protected void VerificaPeriodo()
        {
            try
            {
                TarifaDAL t = new TarifaDAL();

                bool op = Convert.ToBoolean(t.ObterPrimeira(Convert.ToInt32(Session["PeriodoIDTarifasVer"])).S_merc_tarif_porApartamento);

                if (op)
                {
                    RdoTarifa.SelectedValue = "1";
                    ViewState["TipoTarifa"] = "Apartamento";
                }
                else
                {
                    RdoTarifa.SelectedValue = "0";
                    ViewState["TipoTarifa"] = "porpessoa";
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        protected void RdoTarifa_SelectedIndexChanged(object sender, EventArgs e)
        {
            TarifaDAL td = new TarifaDAL();

            if (RdoTarifa.SelectedValue.Equals("1"))
            {
                bool op = Convert.ToBoolean(td.ObterPrimeira(Convert.ToInt32(Session["PeriodoIDTarifasVer"])).S_merc_tarif_porApartamento);

                if (op)
                {
                    GridTarifas.DataSource = td.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), "normal");
                    GridTarifas.DataBind();
                }
                else
                {
                    GridTarifas.DataSource = td.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), "apartamento");
                    GridTarifas.DataBind();
                }
            }
            else
            {
                bool op = Convert.ToBoolean(td.ObterPrimeira(Convert.ToInt32(Session["PeriodoIDTarifasVer"])).S_merc_tarif_porPessoa);

                if (op)
                {
                    GridTarifas.DataSource = td.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), "normal");
                    GridTarifas.DataBind();
                }
                else
                {
                    GridTarifas.DataSource = td.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), "porpessoa");
                    GridTarifas.DataBind();
                }
            }

            MergeCells();
        }

        private void MergeCells()
        {
            int i = GridTarifas.Rows.Count - 2;
            while (i >= 0)
            {
                GridViewRow curRow = GridTarifas.Rows[i];
                GridViewRow preRow = GridTarifas.Rows[i + 1];

                int j = 0;
                while (j < curRow.Cells.Count)
                {
                    if (curRow.Cells[j].Text == preRow.Cells[j].Text)
                    {
                        if (preRow.Cells[j].RowSpan < 2)
                        {
                            curRow.Cells[j].RowSpan = 2;
                            preRow.Cells[j].Visible = false;
                        }
                        else
                        {
                            curRow.Cells[j].RowSpan = preRow.Cells[j].RowSpan + 1;
                            preRow.Cells[j].Visible = false;
                        }
                    }
                    j++;
                }
                i--;
            }
        }

        #endregion

        #region Carrega Dados Meal

        protected void CarregarDadosMeal(object sender, EventArgs e)
        {
            CarregarMeal(sender, e);
        }

        protected void CarregarMeal(object sender, EventArgs e)
        {
            try
            {
                MealDAL m = new MealDAL();
                SBasesDAL sbd = new SBasesDAL();
                STarifaBaseDAL stbd = new STarifaBaseDAL();

                if (sbd.ObterPorIdSupplier(Convert.ToInt32(Session["Sid"])).Count() != 0)
                {

                    S_Tarifa_Base st = stbd.ObterPorId(Convert.ToInt32(ViewState["IdTarifaBase"]));

                    if (st != null)
                    {
                        GridMeal.DataSource = m.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), Convert.ToInt32(ViewState["IdTarifaBase"]));
                        GridMeal.DataBind();
                    }
                    else
                    {
                        GridMeal.DataSource = m.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]), 0);
                        GridMeal.DataBind();
                    }
                }
                else
                {
                    GridMeal.DataSource = m.ListarTodos(Convert.ToInt32(Session["PeriodoIDTarifasVer"]));
                    GridMeal.DataBind(); //Desenhar
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void PaginarDadosMeal(object sender, GridViewPageEventArgs e)
        {
            //Realiza a paginação
            GridMeal.PageIndex = e.NewPageIndex;
            CarregarDadosMeal(sender, e); //Atualizar os dados do GridView
        }

        #endregion

        #region Regras Bases

        protected void PopulaGridBase()
        {
            try
            {
                SupplierDAL sp = new SupplierDAL();
                SBasesDAL bd = new SBasesDAL();

                GridBases.DataSource = bd.ObterPorIdSupplier(Convert.ToInt32(Session["Sid"]));
                GridBases.DataBind();

                GridBases.SelectedIndex = 0;


                foreach (GridViewRow row in GridBases.Rows)
                {
                    ViewState["IdTarifaBase"] = row.Cells[0].Text;
                    break;
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void GridBases_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ViewState["IdTarifaBase"] = Convert.ToInt32(GridBases.SelectedRow.Cells[0].Text);

                CarregarMeal(sender, e);
                CarregarTarifas(sender, e);

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void VerificaBase()
        {
            try
            {
                SBasesDAL sbd = new SBasesDAL();
                SupplierDAL sd = new SupplierDAL();

                if (sbd.ObterPorIdSupplier(Convert.ToInt32(Session["Sid"])).Count() != 0)
                {
                    PopulaGridBase();
                }
                else
                {
                    lblSemBaseTXT.Text = "Este supplier não tem base cadastrada.";
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        #endregion

        #region Regras

        public void PreencheTitulos()
        {
            Dictionary<string, string> titulos = (Dictionary<string, string>)Session["TitulosTarifasVer"];

            lblSupplierTarifa.Text = Convert.ToString(Session["Snome"]);
            lblMercado.Text = titulos["Mercado"];
            lblResponsavel.Text = titulos["Responsavel"];
            lblBaseTarifaria.Text = titulos["Base"];
            lblMoeda.Text = titulos["Moeda"];
        }

        #endregion


    }
}